package alert

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryAlertRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryAlertRuleLogic 查询告警规则
func NewQueryAlertRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAlertRuleLogic {
	return &QueryAlertRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryAlertRuleLogic) QueryAlertRule(req *types.QueryAlertRuleRequest) (resp *types.QueryAlertRuleResponse, err error) {
	var alertRules []*types.AlertRule

	if len(req.ID) > 0 {
		// 查询单条或多条通知
		for _, id := range req.ID {
			notification, err := l.svcCtx.AlertRuleModel.FindOne(id)
			if err != nil {
				if errors.Is(err, sqlc.ErrNotFound) {
					continue
				}
				logx.Errorf("查询告警规则配置数据失败，ID: %d, 错误: %v", id, err)
				return &types.QueryAlertRuleResponse{
					Success: 500,
					Message: "Failed to find alert rule, " + err.Error(),
				}, err
			}
			alertRules = append(alertRules, notification)
		}

		if len(alertRules) == 0 {
			return &types.QueryAlertRuleResponse{
				Success: 500,
				Message: fmt.Sprintf("数据库中未找到相关数据，ID: %d", req.ID),
			}, err
		}
	} else if req.All {
		// 查询全部通知
		allAlertRules, err := l.svcCtx.AlertRuleModel.FindAllEnabled()
		if err != nil {
			logx.Errorf("查询所有告警规则配置数据失败，错误: %v", err)
			return &types.QueryAlertRuleResponse{
				Success: 500,
				Message: "查询所有告警规则配置数据失败, " + err.Error(),
			}, err
		}
		for _, alertRule := range allAlertRules {
			alertRules = append(alertRules, &alertRule)
		}

		// 检查是否有通知被找到
		if len(alertRules) == 0 {
			return &types.QueryAlertRuleResponse{
				Success: 500,
				Message: "No alert rule found",
			}, nil
		}
	} else {
		return &types.QueryAlertRuleResponse{
			Success: 500,
			Message: "无效请求，请提供 ID 或将 All 设为 true",
		}, nil
	}

	return &types.QueryAlertRuleResponse{
		Success:    200,
		Message:    "查询告警规则成功",
		AlertRules: alertRules,
	}, nil
}
